from pyecharts.charts import Pie, Bar
import pandas as pd
import pyecharts.options as opts
from pymongo import MongoClient


def readData():
    client = MongoClient('mongodb://localhost:27017/')
    db = client['JD']  # 替换为你的数据库名
    collection = db['JD_data']  # 替换为你的集合名
    # 将数据加载到Pandas DataFrame
    data = collection.find()
    df = pd.DataFrame(list(data))
    df.drop(columns='_id', inplace=True)

    print(df)
    return df

def main(df):

    # 统计每个品牌的销售占比
    data = df.groupby(['品牌'])['售出'].count()
    data = data.sort_values(ascending=False)

    pie = (
        Pie(init_opts=opts.InitOpts(width='1200px', height='600px'))
        .add('', [v for v in zip(list(data.index), [int(i) for i in data.values])], radius=['25%', '75%'],
             rosetype='radius')
        .set_global_opts(title_opts=opts.TitleOpts(title='每个品牌的销售占比'),
                         legend_opts=opts.LegendOpts(type_="scroll", pos_left="80%", orient="vertical"))
        .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {d}%"))
    )
    pie.render('pie.html')



    # 统计每个品牌的销售额度
    data = df['品牌']
    sale = df.售出 * df.价格

    df2 = pd.DataFrame([data, sale]).T
    df2.columns = ['品牌', '总销售额']
    data = df2.groupby('品牌')['总销售额'].sum()

    data.sort_values(inplace=True, ascending=False)

    bar = (
        Bar(init_opts=opts.InitOpts(width='1350px', height='600px'))
        .add_xaxis(list(data.index))
        .add_yaxis('', list(data.values), color='lightblue')
        .set_global_opts(title_opts=opts.TitleOpts(title='每个品牌的销的售额度'),
                         datazoom_opts=opts.DataZoomOpts(type_="slider"))
        .set_series_opts(markpoint_opts=opts.MarkPointOpts(
            data=[
                opts.MarkPointItem(type_="min", name="最小值"),
                opts.MarkPointItem(type_="max", name="最大值"),
                opts.MarkPointItem(type_="average", name="平均值"),
            ]
        )

        )
    )

    bar.render('bar.html')

    # 统计售价最高前十的品牌
    data = df.sort_values(by='价格', ascending=False)[:10]
    bar2 = (
        Bar(init_opts=opts.InitOpts(width='1350px', height='600px'))
        .add_xaxis(list(data['品牌'].values))
        .add_yaxis('', list(data['价格'].values))
        .set_global_opts(title_opts=opts.TitleOpts(title='售价最高前十的品牌'))
        .reversal_axis()

    )
    bar2.render('bar2.html')




if __name__ == '__main__':
    df = readData()
    main(df)
